package gs.eisenhower.swallet.ui_component;

import gs.eisenhower.swallet.R;
import gs.eisenhower.swallet.dao.CategoryDao;
import gs.eisenhower.swallet.dao.CategoryDaoImpl;
import gs.eisenhower.swallet.model.Category;
import gs.eisenhower.swallet.utils.constants.WalletConstants;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class CategoryListView extends Activity {
	private String entityType;
	private List<String> categories;
	private ArrayAdapter<String> adapter;
//	private GenericDaoImpl entityTransaction;
	private CategoryDao categoryTransaction;
	private static final int DELETE_BTN = 1;
	
	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_category);
		
		Bundle extras = getIntent().getExtras();
		if (extras == null) {
			return;
		} else {
			entityType = extras.getString("Entity");
			categories = new ArrayList<String>(extras.getStringArrayList("Categories"));
			
			ListView categoryListView = (ListView) findViewById(R.id.categoryListView);
			adapter = new ArrayAdapter<String>(this, R.layout.list_item, categories);
			categoryListView.setAdapter(adapter);
			
//			entityTransaction = new GenericDaoImpl();
			categoryTransaction = new CategoryDaoImpl();
		}
	}
	    
	@Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
		
	public void closeActivity(View view) {
	    Intent intent = new Intent();
	    intent.putStringArrayListExtra("Categories", (ArrayList<String>)categories);
	    setResult(RESULT_OK, intent);
		
		this.finish();
	}
	
	public void addNewCategory(View view) {
		if (isCategoryEditTextEmpty()) {
			return;
		} else {						
//			Category category = (Category) ModelFactory.getInstance().createModelInstance(Category.class);
			Category category = new Category();
			category.setType(entityType);
			category.setCategory(getNewCategory());
			categoryTransaction.create(category);
			
			EditText editText = (EditText) findViewById(R.id.addEditText);
			String message = WalletConstants.APOSTROPHE
					+ editText.getText().toString() + WalletConstants.APOSTROPHE
					+ " was added";
			editText.setText("");
			
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
			
			updateListOfCategories();
			
			String title = "New category was added";
			showAlertDialog(title, message, 0);
		}
	}
	
	public void showDeleteDialog(View view) {
		String title   = "Warning";
		String message = "Are you sure you want to delete selected categories?";
		showAlertDialog(title, message, 1);
	}
	
	private void updateListOfCategories() {
		categories.clear();
//		Category category = (Category) ModelFactory.getInstance().createModelInstance(Category.class);
		Category category = new Category();
		category.setType(entityType);
		categories.addAll(categoryTransaction.read(category));
		adapter.notifyDataSetChanged();
	}

	private String getNewCategory() {
		EditText editText = (EditText) findViewById(R.id.addEditText);
		return editText.getText().toString();
	}
	
	public void deleteCategories() {
		ListView listView = (ListView) findViewById(R.id.categoryListView);
        SparseBooleanArray checked = listView.getCheckedItemPositions();
        
        ArrayList<String> selectedItems = new ArrayList<String>();
        for (int i = 0; i < checked.size(); i++) {            
        	int position = checked.keyAt(i);
            if (checked.valueAt(i)) {
                selectedItems.add(adapter.getItem(position));
            }
        }        
		if (selectedItems.size() > 0) {
			categoryTransaction.delete(selectedItems);
			updateListOfCategories();
			listView.clearChoices();
		}
	}
	
    private boolean isCategoryEditTextEmpty() {
		EditText categoryEditText = (EditText) findViewById(R.id.addEditText);
    	if (categoryEditText.getText().toString().equals("")) {
    		return true;
    	} else {
    		return false;
    	}
	}
    
	private void showAlertDialog(String title, String message, int identif) {
		ContextThemeWrapper dialogTheme = new ContextThemeWrapper(this, android.R.style.Theme_Holo);
		AlertDialog.Builder alertDialogBuilder =  new AlertDialog.Builder(dialogTheme);
		
		alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage(message);
		
		if (identif == DELETE_BTN) {
			alertDialogBuilder.setPositiveButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
		}
		alertDialogBuilder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				deleteCategories();
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}
